﻿using UnityEngine;

namespace GameDesigner
{
    public class AnimationStateMachine : IAnimationHandler
    {
        private Animation animation;
        private float elapsedTime;
        private float normalizedTime;

        public AnimationStateMachine(Animation animation, StateLayer layer)
        {
            this.animation = animation;
        }

        public void SetParams(params object[] args) //中途修改动画对象用
        {
            animation = args[0] as Animation;
        }

        public void OnInitializeBegin(IStateMachine stateMachine)
        {
            ApplyLayerMask();
            ApplyLayerWeight(false);
        }

        public void OnInitializeEnd(IStateMachine stateMachine)
        {
        }

        public void OnPlayAnimation(State state, StateAction stateAction)
        {
            var clipName = stateAction.clipName;
            stateAction.animTime = 0f;
            var animState = animation[clipName];
            animState.speed = state.animSpeed;
            elapsedTime = 0f;
            normalizedTime = 0f;
            if (state.isCrossFade)
            {
                animation.CrossFade(clipName, state.duration);
            }
            else
            {
                animation.Play(clipName);
                animState.time = 0f;
            }
        }

        public bool OnAnimationUpdate(State state, StateAction stateAction, StateMachineUpdateMode currMode)
        {
            if (currMode == StateMachineUpdateMode.Update)
            {
                if (stateAction.length <= 0f)
                {
                    var clipName = stateAction.clipName;
                    var animState = animation[clipName];
                    stateAction.length = animState.length;
                }
                elapsedTime += Time.deltaTime * state.animSpeed;
                normalizedTime = elapsedTime / stateAction.length;
                stateAction.animTime = normalizedTime / 1f * 100f;
            }
            return animation.isPlaying;
        }

        public void OnAnimationEnd(State state, StateAction stateAction) { }

        public void ApplyLayerMask() { }

        public void ApplyLayerWeight(bool isCrossFade = true) { }

        public void OnStateEnter(State state) { }

        public void OnStateUpdate(State state, StateMachineUpdateMode currMode) { }

        public void OnStateExit(State state) { }
    }
}